package data

import (
	"context"
	"time"

	"github.com/go-kratos/kratos/v2/log"

	"gitee.com/danqingzhao/go-dango/apps/user/biz"
	"gitee.com/danqingzhao/go-dango/pkg/proto/settings"
	"gitee.com/danqingzhao/go-dango/pkg/third/orm"
)

type permissionRepo struct {
	data *Data
	log  *log.Helper
}

func NewPermissionRepo(data *Data, logHelpers *settings.LogHelpers) biz.PermissionRepo {
	return &permissionRepo{data: data, log: logHelpers.Data}
}

func (r *permissionRepo) CreateModel(ctx context.Context, m *biz.PermissionModel) error {
	now := time.Now()
	m.CreatedAt = now
	m.UpdatedAt = now
	if err := orm.DBCreate(ctx, r.data.gormDB, &biz.PermissionModel{}, m); err != nil {
		r.log.WithContext(ctx).Error(err.Error())
		return err
	}
	return nil
}

func (r *permissionRepo) UpdateModel(ctx context.Context, m biz.PermissionModel, conds ...any) error {
	m.UpdatedAt = time.Now()
	if err := orm.DBUpdate(ctx, r.data.gormDB, &m, &biz.PermissionModel{}, nil, conds...); err != nil {
		r.log.WithContext(ctx).Error(err.Error())
		return err
	}
	return nil
}

func (r *permissionRepo) DeleteModel(ctx context.Context, conds ...any) error {
	if err := orm.DBDelete(ctx, r.data.gormDB, &biz.PermissionModel{}, conds...); err != nil {
		r.log.WithContext(ctx).Error(err.Error())
		return err
	}
	return nil
}

func (r *permissionRepo) FindModel(
	ctx context.Context,
	preloads []string,
	conds ...any,
) (*biz.PermissionModel, error) {
	var m biz.PermissionModel
	if err := orm.DBFind(ctx, r.data.gormDB, preloads, &m, conds...); err != nil {
		r.log.WithContext(ctx).Error(err.Error())
		return nil, err
	}
	return &m, nil
}

func (r *permissionRepo) ListModel(
	ctx context.Context,
	qp orm.QueryParams,
) (int64, []biz.PermissionModel, error) {
	var ms []biz.PermissionModel
	count, err := orm.DBList(ctx, r.data.gormDB, &biz.PermissionModel{}, &ms, qp)
	if err != nil {
		r.log.WithContext(ctx).Error(err.Error())
		return 0, nil, err
	}
	return count, ms, nil
}
